import NEV from "./config/config.js";
import Local from '@/library/utils/storage.js';


const defauls = {
	method: "get",
	loading: false
}
function FlushPage(){
	const pages = getCurrentPages() //获取页面列表
	const perpage = pages[pages.length - 1] //当前页   
	perpage.onShow();
	// perpage.onLoad();
}
let isGo = false;
let isLogout = false;
// 全局请求封装
export default (path, data = {}, config = defauls, callFunc) => {
	// console.log('%c请求拦截：', ' background:orange', data);

	const userInfo = Local.GetUserInfo();
	const Authorization = userInfo && userInfo.token ? `Bearer ${userInfo.token}` : "";

	if (config.loading) {
		uni.showLoading({
			title: "加载中",
			mask: true
		});
	};

	return new Promise((resolve, reject) => {
		let task = uni.request({
			header: {
				Authorization
			},
			// url: NEV.BASE_URL + path,
			url: NEV.BASE_URL + path,
			method: config.method,
			data,
			success(response) {
				// console.log('%c响应拦截：', ' background:green', response);
				//用户登录失效
				if (response.data.code === 401) {
					console.log('登录失效');
					if (isLogout) {

					} else {
						isLogout = true; // 标记是否登出
						uni.showToast({
							title: '登陆过期',
							icon: 'none'
						})
						Local.ClearUserInfo();
						FlushPage();
					}

				}
				// if (response.data.code === 3001) {
				// 	// logout()
				// }
				if (response.data.code !== 20) {
					// uni.showToast({
					// 	icon: "none",
					// 	duration: 4000,
					// 	title: response.data.message
					// });
				}
				if (response.data.message == '更新成功') response.data.message = '修改成功'
				resolve(response.data);
			},
			fail(err) {
				// console.log('dddddddddddddddd')
				if (err.errMsg == "request:fail abort") {
					resolve(null);
					return;
				};
				uni.showToast({
					icon: "none",
					title: '服务响应失败',
					duration: 3000
				});
				console.log(err);
				resolve(false);
			},
			complete(res) {
				// console.log('a',res)
				if (502 == res.statusCode) {
					resolve({
						message: '服务响应失败'
					});
					// console.log('dddd',isGo)
					if (!isGo) {
						isGo = true;
						let pages = getCurrentPages();
						let page = pages[pages.length - 1]
						// console.log(page)
						if (page && page.route && 'pagesNotLogin/netstate/netstate' != page.route) {
							// uni.navigateTo({
							// 	url: '/pagesNotLogin/netstate/netstate',
							// 	success() {
							// 		// console.log('dddd',isGo)
							// 		// isGo = false;
							// 	}
							// })
						}
					}
				} else {
					uni.hideLoading();
				}

			}
		});
		if (task && callFunc && typeof callFunc === "function") {
			callFunc(task)
		}
	});
};